import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';

import { CommonService } from '../../../services-common/common.service';
import { defalutImg } from 'src/app/comm';
import { LoveOrderManageService } from '../love-order-manage.service';
import { getLodop } from 'src/assets/LodopFuncs';
import { purchaseChannelLists } from '../machine-inspection-items';
import { PermissionService } from 'src/app/service/permission.service';

@Component({
  selector: 'app-inspected-machine',
  templateUrl: './inspected-machine.component.html',
  styleUrls: ['./inspected-machine.component.scss']
})
export class InspectedMachineComponent implements OnInit {
  @ViewChild('detailRef') detailRef: any;
  @ViewChild('reportModalRef') reportModalRef: any;

  routerParams: any = {};
  cardSize: any = 'default';
  fallback: string = defalutImg;
  batchDefaultImg: string = '../../../../assets/images/batch-default.png';

  // 订单详情
  orderDetailsData: any = {};
  // 机型估价详情
  orderRecycleModel: any = {};
  // 订单动态
  orderDynamic: any = [];
  // 跟进信息
  followTableData: any = [];
  // 机器验机详情list
  machineDetailsTable: any = [];

  // 评估情况list ueval
  situationLists: any = [];

  // 异常Modal
  isAbnormalVisible: boolean = false;
  abnormalForm!: FormGroup;

  // 添加跟进
  isFollowVisible: boolean = false;
  followForm!: FormGroup;

  // 查看评估详情 Modal
  previewParams = {
    moduleId: '', // 机型ID
    evalList: [], // 对比项
    umname: '', // 机型名称
    totalNum: 0 // 预估合计
  }

  // 打印
  payChannelList: any = [...purchaseChannelLists]; // 购买渠道版本
  LODOP: any;
  deviceInfo = {
    type: '',
    color: '',
    memory: '',
    version: '',
    network: '',
    serial: '',
    serialNumber: '',
    imei: '',
    chargeCount: '',
    batteryHealth: '',
  };

  // 加价设置 Modal
  makeupVisible = false;

  // 修改验机详情
  isEditDetailsVisible = false;
  subEditDetailsLoading = false;
  editDetailsText = '';

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private modal: NzModalService,
    private message: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private services: LoveOrderManageService,
    private commonService: CommonService,
    public permission: PermissionService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    })
  }

  async ngOnInit() {
    // 异常
    this.abnormalForm = this.fb.group({
      type: ['', [Validators.required]],
      isReturn: ['', [Validators.required]],
      location: ['', [Validators.required]]
    });

    // 添加跟进
    this.followForm = this.fb.group({
      remarks: ['', [Validators.required]]
    });

   await this.loadDetailsData();

    setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      if (!this.LODOP) {
        this.message.warning('未安装打印插件');
        return;
      }
      let count = 0;
      for (let i = 0; i < this.LODOP.GET_PRINTER_COUNT(); i++) {
        if (this.LODOP.GET_PRINTER_NAME(i).includes('BTP')) {
          count += 1;
          this.LODOP.SET_PRINTER_INDEXA(i);
        }
      }
      if (count === 0) {
        this.message.warning('未找到包含BTP的打印机，请手动设置');
      } else if (count === 1) {
        this.message.success('打印机初始化成功');
      } else if (count > 1) {
        this.message.success('找到两台包含BTP的打印机，将选择最后一台作为默认设备');
      }
    }, 1000);
  }

  // 详情loadData
  async loadDetailsData() {
    const msgId = this.message.loading('加载中..', { nzDuration: 0 }).messageId;
    const res: any = await this.services.getOrderDetails({id: this.routerParams.id});
    this.message.remove(msgId);

    if (res.code == 0) {
      const { evalList, followInfo, phoneCheckList, orderInfo, recycleModel } = res.data || {};
      this.orderDynamic = orderInfo.dynamic ? JSON.parse(orderInfo.dynamic) : [];
      this.orderDetailsData = orderInfo || {};
      this.followTableData = followInfo || []; // 跟进
      this.machineDetailsTable = phoneCheckList || []; // 机器验机详情
      this.situationLists = orderInfo?.ueval ? JSON.parse(orderInfo?.ueval) : []; // 评估情况list
      this.orderRecycleModel = recycleModel || {}; // 机型估价详情

      // 评估详情
      this.previewParams.evalList = (evalList && evalList.length) ? evalList : [];
      this.previewParams.moduleId = orderInfo?.umid || '';
      this.previewParams.totalNum = (Number(orderInfo.uprc) || 0) + (Number(orderInfo.orderAprc) || 0);
      this.previewParams.umname = orderInfo.umname || '';
    } else {
      this.message.error(res.message);
    }
  }

  showModal() {}
  handleCancel() {}
  submitForm() {}

  // 推送报告
  showConfirm() {
    let sumNum = this.machineReduce(this.machineDetailsTable) + (this.orderDetailsData.aprc || 0) + (this.orderDetailsData.cprc || 0);
    this.modal.confirm({
      nzTitle: '推送验机报告',
      nzContent: `<b>是否将验机结果推送给用户，成交后用户将获得 ${sumNum} 元</b>`,
      nzOnOk: async () => {
        let params = {
          okey: this.orderDetailsData.okey // 订单号
        }
        const res: any = await this.services.pushReportData(params);
        if (res.code == 0) {
          this.loadDetailsData();
          setTimeout(() => {
            this.message.success('推送成功');
          }, 200);
        } else {
          this.message.error(res.message);
        }
      }
    });
  }

  /**
   * ----------------------------------------------------------------
   * 跟进 Modal
   * ----------------------------------------------------------------
   */
  showFollowModal() {
    this.followForm.reset();
    this.isFollowVisible = true;
  }
  followCancel() {
    this.isFollowVisible = false;
  }
  async submitFollow() {
    if (this.followForm.valid) {
      let params = {
        ...this.followForm.value,
        id: this.routerParams.id
      }
      const res: any = await this.services.orderFollowUpData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.isFollowVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.followForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 跳转验机报告页面
   * @param type 0：新增，1：编辑，2：查看
   */
  async jumpReport(type: number, item?: any) {
    let userInfo = JSON.parse((localStorage as any).getItem('userInfos')) || {};
    if (
      [0, 1].includes(type) &&
      this.orderDetailsData.checkName &&
      userInfo.realName != this.orderDetailsData.checkName
    ) {
      this.message.warning('您不是当前订单验机师，不可操作!');
      return
    }

    let routerParams: any = {
      machineListSize: this.machineDetailsTable?.length || '0',
      ostat: this.orderDetailsData.ostat || '',
      type: type,
      okey: this.orderDetailsData.okey || '', // 订单号
      previewParams: JSON.stringify(this.previewParams), // 查看评估详情params
      recycleModel: JSON.stringify(this.orderRecycleModel), // 机型估价详情
      orderWay: this.orderDetailsData.orderWay,
      modelInfos: JSON.stringify({
        modelId: this.orderDetailsData.umid,
        modelName: this.orderDetailsData.umname
      }),
      assessmentDetails: JSON.stringify({
        orderWay: this.orderDetailsData.orderWay,
        umname: this.orderDetailsData.umname,
        uprc: this.orderDetailsData.uprc, // 评估价
        orderAprc: this.orderDetailsData.orderAprc, // 评估加价
        aprc: this.orderDetailsData.aprc, // 验机加价
        cprc: this.orderDetailsData.cprc, // 回收下单抽奖
        ueval: JSON.parse(this.orderDetailsData.ueval) // 评估情况
      }) // 机器评估详情
    }

    if ([1, 2].includes(type)) {
      routerParams.id = item.id;
    }
    // return
    if (type == 0 && !this.orderDetailsData?.checkName) {
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: '当前操作将会把订单锁定在你名下，非验机师请勿操作！',
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: async () => {
          const res: any = await this.services.lockingWorkerData(this.orderDetailsData.okey);
          if (res.code == 0) {
            this.message.success('验机师已锁定验机订单');
            this.router.navigate(['/aisi-recyc/inspectedMachineEdit'],{
              queryParams: {...routerParams}
            })
          } else {
            this.message.error(res.message);
          }
        },
        nzCancelText: '取消'
      });
      return
    }
    this.router.navigate(['/aisi-recyc/inspectedMachineEdit'],{
      queryParams: {...routerParams}
    })
  }

  // 查看评估详情
  assessPreview() {
    this.detailRef.getSubjectList();
    this.detailRef.isVisible = true;
  }

  // 验机详情合计
  machineReduce(arrs: any[]) {
    let sum = 0;
    if (arrs.length) {
      sum = arrs.reduce((total, item) => {
        return total + (item.price || 0)
      }, 0)
    }
    return sum;
  }

  setPrint() {
    this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
    this.LODOP.SELECT_PRINTER();
  }

  // 打印标签
  print(data: any) {
    let channelObj = this.payChannelList.find((item: any) => { return item.value == data.buyType });
    this.deviceInfo = {
      type: data.modelName, // 名称
      color: data.colour, // 颜色
      memory: data.store, // 内存
      version: channelObj?.label || '--', // 购买渠道版本
      network: data.net, // 网络
      serial: data.phoneCode,
      serialNumber: data.phoneSerialNumber,
      imei: data?.imel || '',
      chargeCount: data?.chargeCount || '',
      batteryHealth: data?.batteryHealth || '',
    };

    setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      this.LODOP.SET_LICENSES('', 'D4E01F380814536C3C4887A0707CBBD4A4B', '', '');
      this.LODOP.SET_PRINT_PAGESIZE(1, 500, 250);
      this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printDeviceInfo')?.innerHTML);
      this.LODOP.PRINT();
    })
    // if (this.dbclick) {
    //   clearTimeout(this.dbclick);
    //   this.dbclick = null;
    //   this.LODOP.PREVIEW();
    //   return;
    // }
    // this.dbclick = setTimeout(() => {
    //   this.LODOP.PRINT();
    //   this.dbclick = null;
    // }, 500);
  }

  // 机器评估详情查看
  returnParames() {
    let params = {
      operationType: 'verifyView',
      optionIds: this.orderDetailsData.ueval ? JSON.parse(this.orderDetailsData.ueval).map((item: any) => item.id) : [],
      assessTypeInfo: JSON.stringify(this.orderRecycleModel) || {}
    }
    return params;
  }

  // 查看验机报告
  showReportModal(item: any) {
    let params = {
      phoneCode: item.phoneCode // 机器编号
    }
    this.reportModalRef.loadData(params);
    this.reportModalRef.isVisible = true;
  }

  // 删除机器验机详情list
  async deleteTestMachine(item: any) {
    const res: any = await this.services.deletePhoneCheckData({id: item.id});
    if (res.code == 0) {
      this.loadDetailsData();
      this.message.success('删除成功');
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 加价设置 Modal
   * ----------------------------------------------------------------
   */
  showMakeupModal() {
    this.makeupVisible = true;
  }
  submitSetupCoupon(res: any) {
    this.loadDetailsData();
  }

  // 机器验机详情验机加价合计
  machineMakeupSum() {
    let sum = 0;
    if (this.machineDetailsTable.length) {
      sum = this.machineDetailsTable.reduce((total: number, item: any) => {
        return total + (item.aprc || 0);
      }, 0)
    }
    return sum;
  }

  // Copy
  copyText(str: any) {
    this.commonService.copyStr(str);
  }

  /**
   * 修改验机详情 Modal
   * ----------------------------------------------------------------
   */
  showEditDetailsModal() {
    this.editDetailsText = '';
    this.isEditDetailsVisible = true;
  }

  async subEditDetailsData() {
    if (this.commonService.isEmpty(this.editDetailsText)) {
      this.message.warning('请先输入原因');
      return
    }
    const params = {
      oKey: this.orderDetailsData.okey, // 订单编号
      note: this.editDetailsText
    }
    this.subEditDetailsLoading = true;
    const {code, data}: any = await this.services.backEditDetailsData(params);
    this.subEditDetailsLoading = false;

    if (code === 0) {
      this.isEditDetailsVisible = false;
      this.message.success('修改成功');
      this.loadDetailsData();
    }
  }
}
